package com.wushijia.highconcurrency.lock;

import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.StampedLock;

public class StampedLockDemo1 {

  static Thread[] holdCpuThreads = new Thread[3];
  static final StampedLock lock = new StampedLock();
  public static void main(String[] args) throws InterruptedException {
    new Thread(() -> {
      long writeLong = lock.writeLock();
      LockSupport.parkNanos(600000000000L);//阻塞600秒
      lock.unlock(writeLong);
    }).start();
    Thread.sleep(100);
    for (int i = 0; i < holdCpuThreads.length; i++) {
      holdCpuThreads[i] = new Thread(new HoldCpuThread());
      holdCpuThreads[i].start();
    }
    Thread.sleep(10000);
    //线程中断后，会再次进入循环（类似于CAS死循环反复尝试的策略），会占用cpu
    for (Thread holdCpuThread : holdCpuThreads) {
      holdCpuThread.interrupt();
    }
  }

  private static class HoldCpuThread implements Runnable{

    @Override
    public void run() {
      long readLong = lock.readLock();
      System.out.println(Thread.currentThread().getName()+"获得读锁");
      lock.unlockRead(readLong);
    }
  }
}
